package com.example.pdfutils.controller;

import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfBlendMode;
import com.spire.pdf.graphics.PdfTemplate;

import java.awt.geom.Dimension2D;
import java.awt.geom.Point2D;
import java.io.File;

/**
 * 两张pdf合并示例
 * 选取或者制作一张A4白色pdf
 * 通过A4模板进行drawTemplate操作即可
 *
 * @author yuyong
 * @version 1.0
 * @date 2022-12-30
 */
public class MergeTest {

    public static void main(String[] args) {


        String path = System.getProperty("user.dir") + File.separator;
        double borderWidthSize = 10;

        // 一张a4 pdf白色背景
        PdfDocument a4Pdf = new PdfDocument();
        a4Pdf.loadFromFile(path + "a4Pdf.pdf");


        //根据的第一页绘制模板
        PdfPageBase pdfPageBase = a4Pdf.getPages().get(0);
        pdfPageBase.getCanvas().setTransparency(1f, 1f, PdfBlendMode.Normal);

        PdfTemplate template = a4Pdf.getPages().get(0).createTemplate();
        Dimension2D size = template.getSize();
        double height = size.getHeight();
        double width = size.getWidth();
        double maxWidth = width - borderWidthSize * 2;

        PdfDocument pdf1 = new PdfDocument();
        // 需要合并的两张pdf
        pdf1.loadFromFile(path + "小米移动 电子发票-202112.pdf");
        PdfDocument pdf2 = new PdfDocument();
        pdf2.loadFromFile(path + "小米移动 电子发票-202201.pdf");

        //获取pdf2的第二页
        PdfPageBase page1 = pdf1.getPages().get(0);
        PdfTemplate template1 = page1.createTemplate();
        // reset size
        Dimension2D resetSize = template1.getSize();
        if (resetSize.getWidth() > maxWidth) {
            // 缩小pdf的宽度为a4纸的宽度
            double b = resetSize.getHeight() / resetSize.getWidth();
            resetSize.setSize(maxWidth, maxWidth * b);
        }

        double px = (maxWidth - resetSize.getWidth()) / 2;
        px = px + borderWidthSize;
        double py = (height / 2 - resetSize.getHeight()) / 2;
        pdfPageBase.getCanvas().drawTemplate(template1, new Point2D.Float((float) px, (float) py));


        page1 = pdf2.getPages().get(0);
        template1 = page1.createTemplate();
        // reset size
        resetSize = template1.getSize();
        if (resetSize.getWidth() > maxWidth) {
            // 缩小pdf的宽度为a4纸的宽度
            double b = resetSize.getHeight() / resetSize.getWidth();
            resetSize.setSize(maxWidth, maxWidth * b);
        }

        px = (maxWidth - resetSize.getWidth()) / 2;
        px = px + borderWidthSize;
        py = (height / 2 - resetSize.getHeight()) / 2;
        py = py + (height / 2);
        pdfPageBase.getCanvas().drawTemplate(template1, new Point2D.Float((float) px, (float) py));

        //保存pdf2
        a4Pdf.saveToFile(path + "MergePages.pdf", FileFormat.PDF);
        a4Pdf.dispose();
    }

}
